package edu.ustb.efws.pipeline.collect.handler;

import edu.ustb.efws.EfwsProperties;
import edu.ustb.efws.pipeline.collect.Collect;
import edu.ustb.efws.pipeline.collect.cache.ThosCache;
import edu.ustb.efws.pipeline.domain.Thos;
import edu.ustb.efws.pipeline.domain.ThosLog;
import edu.ustb.efws.pipeline.service.ThosLogService;
import edu.ustb.efws.utils.DateUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 温湿度传感器数据处理
 *
 * @author TS Group
 */
class ThosLogHandler implements PipelineHandler {
    private final ThosLogService service;
    private final EfwsProperties properties;

    ThosLogHandler(ThosLogService service, EfwsProperties properties) {
        this.service = service;
        this.properties = properties;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Optional<Object> handle0(Object data) {
        Collect collect = (Collect)data;
        List<Thos> tHOSs= (List<Thos>)collect.getData();
        if(tHOSs == null || tHOSs.isEmpty()){
            return Optional.empty();
        }

        tHOSs = filterWorkTime(tHOSs);
        if(tHOSs.isEmpty()){
            return Optional.empty();
        }

        List<ThosLog> logs = tHOSs.stream().map(this::buildLog).collect(Collectors.toList());
        service.save(collect.getColTableName(), logs);
        return Optional.of(logs);
    }

    private List<Thos> filterWorkTime(List<Thos> logs){
        return logs.stream().filter(e -> {
            LocalDateTime localDateTime = DateUtils.dateToLocalDataTime(e.getTime());
            int minute = localDateTime.getHour() * 60 + localDateTime.getMinute();
            return minute >= properties.getMeterStartMinute() && minute <= properties.getMeterEndMinute();
        }).collect(Collectors.toList());
    }

    private ThosLog buildLog(Thos t){
        ThosLog log = new ThosLog();

        log.setDetectorId(t.getDetectorId());
        log.setMonth(DateUtils.dateToMonthNum(t.getTime()));
        log.setH(t.getH());
        log.setO(t.getO());
        log.setT(t.getT());
        log.setCollectTime(t.getTime());

        //更新缓存数据
        updateCache(t);

        return log;
    }

    private void updateCache(Thos t){
        ThosCache.INSTANCE.push(t);
    }
}
